package com.atguigu.controller;

import com.atguigu.client.CartFeignClient;
import com.atguigu.client.UserFeignClient;
import com.atguigu.entity.*;
import com.atguigu.enums.OrderStatus;
import com.atguigu.enums.ProcessStatus;
import com.atguigu.result.RetVal;
import com.atguigu.service.OrderDetailService;
import com.atguigu.service.OrderInfoService;
import com.atguigu.util.AuthContextHolder;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * OrderController
 *
 * @author yangchao
 * @version 开发阶段
 * @description TODO
 * @date 2022/3/8 23:44
 */
@RestController
@RequestMapping("/order")
public class OrderController {

    @Autowired
    private UserFeignClient userFeignClient;
    @Autowired
    private CartFeignClient cartFeignClient;
    @Autowired
    private OrderInfoService orderService;
    @Autowired
    private OrderDetailService orderDetailService;
    //1 .订单确认信息接口
    @GetMapping("/confirm")
    public RetVal<Map<String, Object>>  confirm(HttpServletRequest request){
        //a.用户的收货地址列表
        String userId = AuthContextHolder.getUserId(request);
        List<UserAddress> userAddressList = userFeignClient.getAddressByUserId(userId);
        //b.在购物车勾选的商品--送货清单
        List<CartInfo> selectedProductList = cartFeignClient.getSelectedProduct(userId);
        //订单总金额
        BigDecimal totalMoney=new BigDecimal(0);
        //商品总的数量
        int totalNum=0;
        //订单详情list
        ArrayList<OrderDetail> orderDetailList = new ArrayList<>();
        if(!CollectionUtils.isEmpty(selectedProductList)){
            for (CartInfo cartInfo : selectedProductList) {
                //设置商品详情信息
                OrderDetail orderDetail = new OrderDetail();
                orderDetail.setSkuId(cartInfo.getSkuId());
                orderDetail.setSkuName(cartInfo.getSkuName());
                orderDetail.setImgUrl(cartInfo.getImgUrl());
                orderDetail.setSkuNum(cartInfo.getSkuNum()+"");
                orderDetail.setOrderPrice(cartInfo.getCartPrice());
                //计算订单总金额
                totalMoney=totalMoney.add(cartInfo.getCartPrice().multiply(new BigDecimal(cartInfo.getSkuNum())));
                totalNum+=cartInfo.getSkuNum();
                orderDetailList.add(orderDetail);
            }
        }
        Map<String, Object> retMap = new HashMap<>();
        //地址信息
        retMap.put("userAddressList",userAddressList);
        //订单详情信息
        retMap.put("detailArrayList",orderDetailList);
        //计算订单总金额
        retMap.put("totalMoney",totalMoney);
        //计算订单总数量
        retMap.put("totalNum",totalNum);
        //第二步 点击去结算的时候生成一个流水号
        String tradeNo=orderService.generateTradeNo(userId);  //redis 存
        retMap.put("tradeNo",tradeNo);
        return RetVal.ok(retMap);
    }
    //2.提交订单
    @PostMapping("/submitOrder")
    public RetVal submitOrder(@RequestBody OrderInfo orderInfo, HttpServletRequest request) {
        String userId = AuthContextHolder.getUserId(request);
        //a.返回无刷新不能重复提交订单
        String tradeNo = request.getParameter("tradeNo");
        //判断该交易号是否同redis里面的一致
        boolean flag=orderService.checkTradeNo(tradeNo,userId);
        if(!flag){
            return RetVal.fail().message("不能无刷新回退提交订单");
        }
        //删除交易号
        orderService.deleteTradeNo(userId);

        //b.验证库存和价格
        List<String> warningInfoList = orderService.checkStockAndPrice(userId, orderInfo);
//        //如果有警告信息
        if(warningInfoList.size()>0){
            //org.apache.commons.lang3
            return RetVal.fail().message(StringUtils.join(warningInfoList,","));
        }
        //c.保存订单信息(基本信息/详情信息)
        orderInfo.setUserId(Long.parseLong(userId));
        Long orderId = orderService.saveOrderAndDetail(orderInfo);
        return RetVal.ok(orderId);
    }
    //3.根据订单id查询订单信息
    @GetMapping("/getOrderInfo/{orderId}")
    public OrderInfo getOrderInfo(@PathVariable Long orderId) {
        return orderService.getOrderInfo(orderId);
    }

    //4.订单列表
    @GetMapping("/{pageNo}/{pageSize}")
    public RetVal getOrderPageList(HttpServletRequest request,@PathVariable Integer pageNo,@PathVariable Integer pageSize) {
        String userId = AuthContextHolder.getUserId(request);
        Page<OrderInfo> page = new Page<>(pageNo, pageSize);
        QueryWrapper<OrderInfo> wrapper = new QueryWrapper<>();
        Map<String, Object> map = new HashMap<>();
        map.put("parent_order_id", null);
        wrapper.allEq(map);
        wrapper.orderByDesc("id");
        orderService.page(page,wrapper);
        page.getRecords().forEach(e->{
            QueryWrapper<OrderDetail> orderDetailQueryWrapper = new QueryWrapper<>();
            orderDetailQueryWrapper.eq("order_id",e.getId());
            List<OrderDetail> orderDetailList = orderDetailService.list(orderDetailQueryWrapper);
            e.setOrderDetailList(orderDetailList);
            e.setOrderStatus(OrderStatus.getStatusNameByStatus(e.getOrderStatus()));
            e.setProcessStatus(ProcessStatus.getStatusNameByStatus(e.getProcessStatus()));
        });
        return RetVal.ok(page);
    }

    //5.拆单接口
    @PostMapping("/splitOrder")
    public String splitOrder(@RequestParam Long orderId,@RequestParam String wareHouseIdSkuIdMapJson) {
        //wareHouseIdSkuIdMapJson数据格式: [{"wareHouseId":"1","skuIdList":["18","19"]},{"wareHouseId":"2","skuIdList":["30"]}]
        return orderService.splitOrder(orderId,wareHouseIdSkuIdMapJson);
    }

    //6.保存订单基本信息与详情
    @PostMapping("/saveOrderInfo")
    public Long saveOrderInfo(@RequestBody OrderInfo orderInfo) {
        return orderService.saveOrderAndDetail(orderInfo);
    }


    //订单列表  后台管理使用
    @GetMapping("/Backstage/{pageNo}/{pageSize}")
    public RetVal Backstage(@PathVariable Integer pageNo,@PathVariable Integer pageSize) {
        Page<OrderInfo> page = new Page<>(pageNo, pageSize);
        //查询所有订单，parent_order_id为 空，按照id倒序排列
        QueryWrapper<OrderInfo> wrapper = new QueryWrapper<>();
        Map<String, Object> map = new HashMap<>();
        map.put("parent_order_id", null);
        wrapper.allEq(map);
        wrapper.orderByDesc("id");
        orderService.page(page,wrapper);
        page.getRecords().forEach(e->{
            QueryWrapper<OrderDetail> orderDetailQueryWrapper = new QueryWrapper<>();
            orderDetailQueryWrapper.eq("order_id",e.getId());
            List<OrderDetail> orderDetailList = orderDetailService.list(orderDetailQueryWrapper);
            e.setOrderDetailList(orderDetailList);

            if(StringUtils.isEmpty(e.getOrderComment())){
                e.setOrderComment("买家未设置备注!");
            }
//            if("ONLINE".equals(e.getPaymentWay())){
//                e.setPaymentWay("在线支付");
//            }
//            if("CLOSED".equals(e.getOrderStatus())){
//                e.setOrderStatus("已取消");
//            }
//            if("CLOSED".equals(e.getProcessStatus())){
//                e.setProcessStatus("已关闭");
//            }
            e.setOrderStatus(OrderStatus.getStatusNameByStatus(e.getOrderStatus()));
            e.setProcessStatus(ProcessStatus.getStatusNameByStatus(e.getProcessStatus()));
        });
        return RetVal.ok(page);
    }


}